import axios from 'axios'
import { Message } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import service from '@/utils/request'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API_WEB, // url = base url + request url
  timeout: 500000,
  headers: { 'content-type': 'application/json' }
  // withCredentials: true // send cookies when cross-domain requests
})

// Request interceptors   http request 请求拦截器，有token值则配置上token值
service.interceptors.request.use(
  (config) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    // // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    if (UserModule.token) {
      config.headers['X-Access-Token'] = UserModule.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Request interceptors
/* request.interceptors.request.use(
  (config) => {
    config.data = qs.stringify(config.data)
    return config
  },
  (error) => {
    Promise.reject(error)
  }
) */

// Response interceptors
request.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      Message({
        message: (response.status + response.statusText) || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.data.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token
// 参考：https://codeleading.com/article/56702658499/

export default request
